package com.atguigu.linklist;

public class ReverseEveryKNodes {
    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        head.next=new ListNode(2);
        ListNode node=reverseKGroup(head,2);
        while(node!=null){
            System.out.println(node.val);
            node=node.next;
        }
    }
    public static  ListNode reverseKGroup(ListNode head,int k){
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        ListNode cur=head;
        int len=0;
        while(cur!=null){
            cur=cur.next;
            len++;
        }
        int times=len/k; //需要反转的次数
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //记录上一次的尾节点
        ListNode lastTail = dummy;
        cur = head;
        while(times>0){
            ListNode curTail = cur;
            ListNode pre = null;
            for (int i = 0; i < k; i++) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            //完成后pre为反转后的头结点
            lastTail.next = pre;
            lastTail = curTail;
            times--;
        }
        lastTail.next = cur;
        return dummy.next;
    }

}
